import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import Layout from '@/views/Layout'
import Home from '@/views/Home'
import User from '@/views/User'
import Search from '@/views/Search'
import SearchResult from '@/views/Search/SearchResult'
import ArticleDetail from '@/views/ArticleDetail'
import UserEdit from '@/views/User/UserEdit'
import Chat from '@/views/Chat'
import { getToken } from '@/utils/token'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/layout/home' // 默认显示layou和layou下的首页
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/layout',
    component: Layout,
    children: [
      {
        path: 'home',
        component: Home
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/search',
    component: Search
  },
  { // 搜索结果页
    
    path: '/search_result/:kw',
    component: SearchResult
  },
  { // 文章详情页
    path: '/deteil',
    component: ArticleDetail
  },
  { // 用户编辑
    path: '/user_edit',
    component: UserEdit
  },
  { // 聊天界面
    path: '/chat',
    component: Chat
  }
]

const router = new VueRouter({
  routes
})

// 路由 - 全局前置守卫(在路由发生真正跳转之前,执行此函数)
// 此函数可以决定路由是否跳转/取消/强制中断切换到别的路由
router.beforeEach((to,from,next) => {
  // 需求：如果你已经登陆了,不要切换到登陆页面
  if(getToken()?.length > 0 && to.path === '/login') {
    next(false) // 留在原地/什么都不写
  } else {
    next() // 其他情况放行
  }
})

export default router
